package store.lunangangster.nodeflow.async.local;

import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import store.lunangangster.nodeflow.config.NodeFlowConfig;
import store.lunangangster.nodeflow.exception.SystemInitializationException;

/**
 * 用于并行编排异步执行器的创建
 *
 * @author cwk
 * @version 1.0
 */
public class WhenExecutorBuilder {
	public static ExecutorService createExecutor(NodeFlowConfig config) {
		if (config == null) {
			return null;
		}
		checkExecutorConfig(config);
		Integer minActive = config.getMinActive();
		Integer maxActive = config.getMaxActive();
		Duration keepAliveTime = config.getKeepAliveTime();
		return new ThreadPoolExecutor(minActive, maxActive, keepAliveTime.toNanos(), TimeUnit.NANOSECONDS, new LinkedBlockingQueue<>());
	}

	private static void checkExecutorConfig(NodeFlowConfig config) {
		Integer minActive = config.getMinActive();
		Integer maxActive = config.getMaxActive();
		Duration keepAliveTime = config.getKeepAliveTime();
		if (minActive == null) {
			throw new SystemInitializationException("minActive should not be null");
		}
		if (minActive <= 0) {
			throw new SystemInitializationException("minActive should not be negative or zero");
		}
		if (maxActive == null) {
			throw new SystemInitializationException("maxActive should not be null");
		}
		if (maxActive <= 0) {
			throw new SystemInitializationException("maxActive should not be negative or zero");
		}
		if (keepAliveTime == null) {
			throw new SystemInitializationException("keepAliveTime should not be null");
		}
	}
}
